package logic

import (
	"context"
	"fmt"
	"zy1_user/models/cache"
	"zy1_user/models/mysql"
	"zy1_user/userRpc/internal/svc"
	"zy1_user/userRpc/userRpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginUserLogic {
	return &LoginUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginUserLogic) LoginUser(in *userRpc.LoginUserRequest) (*userRpc.LoginUserResponse, error) {
	// todo: add your logic here and delete this line
	user := mysql.User{}
	mysql.DB.Where("mobile=?", in.Mobile).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("用户不存在")
	}

	sms, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()
	if sms != in.SmsCode {
		return nil, fmt.Errorf("短信验证码错误")
	}
	return &userRpc.LoginUserResponse{
		Id: int64(user.ID),
	}, nil
}
